
package com.huaweicloud.haydn.delivercore.agent.common;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;

import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessErrorEnum;
import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessException;

import lombok.extern.slf4j.Slf4j;

/**
 * 功能描述: 用于校验用户sql中是否存在安全问题
 *
 * @since 2023-03-30
 */
@Slf4j
public class SqlValidateUtils {

    private static String splitPattern = "\\(|\\)|\\{|\\}|,|;|\\s+";

    /**
     * 功能描述:校验用户输入的SQL语句中是否包含篡改数据库数据或者权限的敏感词
     *
     * @param sqlStatement 待校验的SQL语句
     * @since 2023-03-30
     */
    public static void validSqlBadWords(String sqlStatement) {
        String[] splitedSqlArrs = sqlStatement.trim().toUpperCase(Locale.ROOT).split(splitPattern);
        for (String perWordInSql : splitedSqlArrs) {
            if (StringUtils.isNotEmpty(perWordInSql) && AgentConstans.SQL_BAD_WORDS_SET.contains(perWordInSql.trim())) {
                log.error("The SQL statement to be filtered contains invalid characters: {}", perWordInSql);
                throw new BusinessException(BusinessErrorEnum.BASE_BAD_REQUEST,
                    "The SQL statement to be filtered contains invalid characters!");
            }
        }
    }
}
